﻿namespace Ops.Host.App.ViewModels;

public sealed class KibanaViewModel : ObservableObject, IViewModel, IDisposable
{
    private readonly CancellationTokenSource _cts = new();

    private readonly DeviceInfoManager _deviceInfoManager;
    private readonly DeviceHealthManager _deviceHealthManager;

    /// <summary>
    /// 定时器处理对象
    /// </summary>
    public EventHandler? TimerHandler { get; set; }

    public KibanaViewModel(
        DeviceInfoManager deviceInfoManager,
        DeviceHealthManager deviceHealthManager)
    {
        _deviceInfoManager = deviceInfoManager;
        _deviceHealthManager = deviceHealthManager;

        Init();
    }

    void Init()
    {
        var deviceInfos = _deviceInfoManager.GetAll();
        foreach (var deviceInfo in deviceInfos)
        {
            DeviceSourceList.Add(new KibanaModel
            {
                Line = deviceInfo.Schema.Line,
                Station = deviceInfo.Schema.Station,
                ConnectedState = false,
            });
        }

        // 状态检测，定时器可考虑与 DispatcherTimer 有什么差异
        _deviceHealthManager.Check();
        _ = Task.Factory.StartNew(async () =>
        {
            while (!_cts.IsCancellationRequested)
            {
                await Task.Delay(2000);
                ChangeDeviceConnState();
            }

        }, default, TaskCreationOptions.LongRunning, TaskScheduler.FromCurrentSynchronizationContext());

        // 看板动态数据
        _ = Task.Factory.StartNew(async () =>
        {
            while (!_cts.IsCancellationRequested)
            {
                var (ok, msg) = await MessageTaskQueueManager.Default.WaitDequeueAsync();
                if (ok && msg!.Code == MessageClassify.Outbound)
                {
                    if (ProductionSourceList.Count >= 32)
                    {
                        ProductionSourceList.RemoveAt(ProductionSourceList.Count - 1);
                    }

                    var marking = (PtMarkingData)msg.Value!;
                    ProductionSourceList.Insert(0, new()
                    {
                        SN = marking.SN,
                        ProductType = marking.ProductType,
                        MarkerNo = marking.MarkerNo,
                        MarkingTime = marking.MarkingTime,
                        ProductionCountPerDay = marking.ProductionCountPerDay,
                        CreatedTime = marking.CreatedTime,
                        UpdatedTime = marking.UpdatedTime,
                    });
                }
            }
        }, default, TaskCreationOptions.LongRunning, TaskScheduler.FromCurrentSynchronizationContext());
    }

    #region 绑定属性

    private ObservableCollection<KibanaModel> _deviceSourceList = new();

    public ObservableCollection<KibanaModel> DeviceSourceList
    {
        get => _deviceSourceList;
        set => SetProperty(ref _deviceSourceList, value);
    }

    // 生产
    private ObservableCollection<ProductionModel> _productionSourceList = new();

    public ObservableCollection<ProductionModel> ProductionSourceList
    {
        get => _productionSourceList;
        set => SetProperty(ref _productionSourceList, value);
    }

    #endregion

    #region privates

    private void ChangeDeviceConnState()
    {
        foreach (var device in DeviceSourceList)
        {
            var state = _deviceHealthManager.CanConnect(device.Line, device.Station);
            if (device.ConnectedState != state)
            {
                device.ConnectedState = state;
            }
        }
    }

    #endregion

    public void Dispose()
    {
        _cts.Cancel();
    }
}

public class ProductionModel : ObservableObject
{
    public string? SN { get; set; }

    public string? ProductType { get; set; }

    public string? MarkerNo { get; set; }

    public DateTime MarkingTime { get; set; }

    public int? ProductionCountPerDay { get; set; }

    public DateTime CreatedTime { get; set; }

    public DateTime? UpdatedTime { get; set; }
}
